<template>
    <el-dialog v-model="show" title="定稿" align-center width="40%" @close="handleClose">
        <el-row :gutter="20" class="mb8">
            <el-col :span="8">
                订单类别：{{ packageMethod.filter((item: any) => item.value ==
                    props.initList.productType)[0]?.label }}
            </el-col>
            <el-col :span="6">
                客户名称：{{ props.initList.customerName || '' }}
            </el-col>
            <el-col :span="10" style="text-align: right;">
                产品款式：{{ props.initList.customerName || '' }} <span v-if="props.initList.personCount">({{
                    props.personal_ratio.filter((item: any) =>
                        item.value ==
                        props.initList.personCount)[0]?.label
                }})</span>
            </el-col>
        </el-row>
        <el-row :gutter="20" class="mb20">
            <el-col :span="8">
                老客户原稿：<el-link v-if="historyUrl" :href="historyUrl" type="primary">下载原稿信息</el-link>
            </el-col>
            <el-col :span="6">
                设计师：{{ props.initList.designer || '' }}
            </el-col>
            <!-- <el-col :span="10">
                <div class="import_right"><el-button type="primary">一键导入</el-button></div>
            </el-col> -->
        </el-row>

        <el-form :model="form" ref="formRef" label-width="auto">
            <el-row :gutter="10" class="mb8">
                <el-col :span="12">
                    <el-form-item class="designSketch" label="组装效果图:" prop="assemblyRenderingUrl">
                        <el-upload ref="designSketchRef" class="upload-demo" :show-file-list="false" drag
                            :action="uploadImgUrl" :headers="headers" multiple :auto-upload="true"
                            :on-success="handleDesignSketchSuccess" :before-upload="beforedeSignSketchUpload">
                            <img style="height: 100px;" v-if="form.assemblyRenderingUrl"
                                :src="form.assemblyRenderingUrl" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle type="1" icon="PictureFilled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item class="designSketch" label="源文件:" prop="sourceFile">
                        <el-upload ref="sourceFileRef" class="upload-demo" :show-file-list="false" drag
                            :action="uploadImgUrl" :headers="headers" multiple :auto-upload="true"
                            :on-success="handleSourceFileSuccess" :before-upload="beforeSourceFileUpload">
                            <img style="height: 100px;" v-if="form.sourceFile" :src="form.sourceFile" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle type="1" icon="upload-filled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <div class="mb20" v-for="(item, index) in form.relationVos" :key="index">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="6">
                        <div style="line-height: 32px;"><strong>{{ item.specsDetail }}</strong></div>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item label="产品类型" prop="type">
                            <el-select @change="typeChange($event, item, index)" v-model="item.customizedTypeId"
                                placeholder="请选择产品类型">
                                <el-option v-for="dict in props.allDesignerList" :key="dict.id"
                                    :label="dict.customized_name" :value="dict.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <div class="import_right">
                            <el-switch v-model="item.needShow"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="mb8">
                    <el-col class="smallPicture" :span="7">
                        <el-upload ref="sourceFileRef" class="upload-demo" :show-file-list="false" drag
                            :action="uploadImgUrl" :headers="headers" multiple :auto-upload="true"
                            :on-success="(response: any, file: any, fileList: any) => { return handleItemFileSuccess(response, file, fileList, index) }"
                            :before-upload="beforeItemFileUpload">
                            <img style="height: 100px;" v-if="item.fileUrl" :src="item.fileUrl" />
                            <template v-else>
                                <div style="padding-top: 10px;">
                                    <uploadStyle icon="PictureFilled" />
                                </div>
                            </template>
                        </el-upload>
                    </el-col>
                    <el-col :span="17">
                        <el-checkbox-group v-model="item.workProcedureIds" class="groupFlex">
                            <el-checkbox :label="dict.workProcedureId" v-for="dict in item.workVoNoList"
                                :key="dict.workProcedureId"> {{ dict.workProcedureName }} </el-checkbox>
                        </el-checkbox-group>
                    </el-col>
                </el-row>
            </div>

            <el-form-item label="设计绩效" prop="designPerformance">
                <el-input v-model="form.designPerformance" style="width: 240px" placeholder="请输入绩效" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="loading" @click="handleClose">取 消</el-button>
                <el-button :loading="loading" type="primary" @click="handleSubmit">确 认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { type FormInstance, UploadProps } from 'element-plus';
import { ElLoading } from 'element-plus'
import { globalHeaders } from "@/utils/request";
import uploadStyle from './uploadStyle.vue';
import { getDesignerAcceptOrderApi, editDesignerAcceptOrderApi } from '@/api/sj/productManagement/designerTakesOrders/index';
import { getWorkingProcedureListApi } from '@/api/sj/productManagement/finalDraft/index';


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps(['visible', 'initList', 'packageMethod', 'allDesignerList', 'personal_ratio', 'dataDetails']);
const emits = defineEmits(['submit', 'close']);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const dialogVisible = ref();
const show = ref(false);
const historyUrl = ref(''); // 源文件
const loading = ref(false);

const formRef = ref<FormInstance>();
const form = ref<any>({
    designSketch: '', // 效果图
    sourceFile: '', // 源文件
    performance: '', // 绩效
    type: '', // 产品类型
    types: [],
});

const value2 = ref(false);

watch(() => props.visible, async (newValue) => {
    show.value = props.visible
    if (newValue) {
        form.value = props.dataDetails
        historyUrl.value = props.dataDetails.historyUrl
    }
}, { deep: true });

/** 上传效果图 */
const handleDesignSketchSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogVisible.value.close()
    form.value.assemblyRenderingUrl = response.data.url
};

const beforedeSignSketchUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

// 上传源文件
const handleSourceFileSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    dialogVisible.value.close()
    form.value.sourceFile = response.data.url
};

const handleItemFileSuccess: any = (
    response: { data: { url: any; }; }, file: any, fileList: any, index: any
) => {

    dialogVisible.value.close()

    form.value.relationVos[index].fileUrl = response.data.url
};

const beforeSourceFileUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

const beforeItemFileUpload: UploadProps['beforeUpload'] = () => {
    dialogVisible.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
};

/** 选择产品类型 change 事件 获取下面的工序 */

const typeChange = async (e: any, item: any, index: number) => {
    if (e) {
        const data = await getIdsWorkingProcedure(e)
        form.value.relationVos[index].workVoNoList = data
    }
};

/** 根据 id 获取 工序 */
const getIdsWorkingProcedure = (ids: number) => {
    return new Promise<any>(async (resolve, reject) => {
        const { code, data } = await getWorkingProcedureListApi({ id: ids })

        if (code == 200) {
            resolve(data)
        } else {
            reject(false)
        }
    })
}

const handleSubmit = async () => {
    loading.value = true
    try {
        const { code } = await editDesignerAcceptOrderApi(await putData(form.value))

        if (code == 200) {
            emits('submit', false);
            loading.value = false
            proxy?.$modal.msgSuccess('操作成功');
            handleClose()
        }
    } catch (error) {
        loading.value = false
    }

};

/** 修改数据处理 */
const putData = (data: any) => {
    let obj = {
        id: data.designAcceptId,
        assemblyRenderingUrl: data.assemblyRenderingUrl,
        sourceFile: data.sourceFile,
        customizedId: props.initList.id,
        designPerformance: data.designPerformance,
        workBos: []
    }; // 需要返回的

    let list: any = []

    return new Promise<any>(async (resolve, reject) => {
        for (const item of data.relationVos) {
            if (item.needShow) {
                // 选中了,  需要做校验
                if (!item.fileUrl) {
                    proxy?.$modal.msgError(`请上传${item.specsDetail}的图片`);
                    reject(false)
                    break;
                }

                if (item.workProcedureIds.length == 0) {
                    proxy?.$modal.msgError(`请选择${item.specsDetail}的工序`);
                    reject(false)
                    break;

                }
            }

            let newList = {
                needDesign: '',
                customizedTypeId: '',
                fileUrl: '',
                productId: '',
                id: '',
                dataList: []
            }

            newList.customizedTypeId = item.customizedTypeId
            newList.fileUrl = item.fileUrl
            newList.id = item.id
            newList.productId = item.productId
            newList.needDesign = item.needShow ? '1' : '0'

            let dataList: any = []

            item.workProcedureIds.forEach((id: any, index: number) => {
                if (dataList.filter((itemList: any) => itemList.workProcedureId == id).length == 0) {
                    dataList.push({
                        workProcedureId: id,
                        sort: index
                    })
                }
            })

            newList.dataList = dataList

            list.push(newList)
        }

        obj.workBos = list

        resolve(obj)
    })
}

const handleClose = () => {
    formRef.value?.resetFields();
    form.value.relationVos = [];
    loading.value = false;
    emits('close');
};
</script>

<style lang="scss" scoped>
.import_right {
    width: 100%;
    display: flex;
    justify-content: flex-end;
}


::v-deep .designSketch {
    .el-upload-dragger {
        padding: 0px 4px !important;
        height: 100px !important;
        width: 260px;
    }
}

::v-deep .smallPicture {
    .el-upload-dragger {
        padding: 0px 4px !important;
        height: 70px !important;
        width: 190px;
    }
}

.groupFlex {
    height: 70px;
    display: flex;
    align-items: center;
}
</style>